import Phaser from 'phaser';

export default class PlayerSprite extends Phaser.GameObjects.Sprite {
  scene: Phaser.Scene;

  body!: Phaser.Physics.Arcade.Body;

  cursors!: Phaser.Types.Input.Keyboard.CursorKeys;

  constructor(scene: Phaser.Scene, x: number, y: number, texture: string, frame?: string | number) {
    super(scene, x, y, texture, frame);
    this.scene = scene;
    scene.add.existing(this);
    scene.physics.add.existing(this);
    this.body.setBounce(0.2);
    this.body.setCollideWorldBounds(true);
    if (scene.input.keyboard) {
      this.cursors = scene.input.keyboard.createCursorKeys();
    }

    this.init();
  }

  init() {
    this.scene.anims.create({
      key: 'left',
      frames: this.scene.anims.generateFrameNumbers('dude', { start: 0, end: 3 }),
      frameRate: 10,
      repeat: -1,
    });
    this.scene.anims.create({
      key: 'turn',
      frames: [{ key: 'dude', frame: 4 }],
      frameRate: 20,
    });
    this.scene.anims.create({
      key: 'right',
      frames: this.anims.generateFrameNumbers('dude', { start: 5, end: 8 }),
      frameRate: 10,
      repeat: -1,
    });

    this.scene.events.on('update', this.update, this);
  }

  update() {
    if (this.cursors?.left.isDown) {
      this.body.setVelocityX(-160);
      this.anims.play('left', true);
    } else if (this.cursors?.right.isDown) {
      this.body.setVelocityX(160);
      this.anims.play('right', true);
    } else {
      this.body.setVelocityX(0);
      this.anims.play('turn');
    }
    if (this.cursors?.up.isDown && this.body.touching.down) {
      this.body.setVelocityY(-330);
    }
  }
}
